package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.ThemesEditorAbility;
import com.agger.harmonyosthemeseditor.abilities.PreloadServiceAbility;
import com.agger.harmonyosthemeseditor.intelligent.*;
import com.agger.harmonyosthemeseditor.userinterface.GeneralButtonElement;
import com.agger.harmonyosthemeseditor.userinterface.GeneralDialog;
import com.agger.harmonyosthemeseditor.userinterface.GeneralToast;
import com.agger.harmonyosthemeseditor.userinterface.ResourceTool;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.bundle.IBundleManager;
import ohos.data.rdb.ValuesBucket;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.ResourceManager;
import ohos.media.common.Source;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVMetadataHelper;
import ohos.media.photokit.metadata.AVStorage;
import ohos.media.player.Player;
import ohos.os.ProcessManager;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class UnlockPlusSlice extends AbilitySlice
{
    private final int ChooseVideo = 1002;
    Image showImageArea = null;
    TextField textBox_ChineseName = null;
    TextField textBox_InternationalName = null;
    TextField textBox_DesignerName = null;
    TextField textBox_VersionCode = null;
    TextField textBox_BriefInfo = null;
    Component text_ChineseName = null;
    Component text_InternationalName = null;
    Component text_DesignerName = null;
    Component text_VersionCode = null;
    String Dialog_Title = "爱洁羊智慧能力";
    String Dialog_Content_StoragePermissionFailed = "存储功能被禁用，请前往应用管理页，开启主题协作器的存储权限！";
    String Dialog_Button_Cancel = "取消";
    String Dialog_Button_Confirm = "好的";
    String Toast_NoneName = "请录入主题包名称！汉语名称、国际名称，至少填写一项！";
    String Toast_NoneDesigner = "请录入主题包的设计师名称！";
    String Toast_NoneVersion = "请录入主题包的版本号码！";
    String Toast_NoneBriefInfo = "请录入主题包的简单介绍信息！";
    String Toast_NoneVideo = "请先选择视频素材！";
    String Toast_IsProcessing = "主题生成中，请勿进行其它操作！";
    String Toast_Theme_SaveFinish = "主题包已存储至";
    String Toast_Theme_SaveFailed = "存储主题包时出现错误，请确保设备容量充足！";
    MainThreadEventHandler mainThreadEventHandler;
    PacThemeEventHandler PacThemeEventHandler;
    ScreenEventHandler screenEventHandler;
    boolean isProcessing = false;
    boolean VideoCached = false;
    boolean isSuccess = false;
    boolean BigSuccess = false;
    String ThemesDate = "20220222022022";

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation)
    {
        super.onOrientationChanged(displayOrientation);
        try
        {
            DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
            int maxTextWidth = displayAttributes.width-(int)(216f*displayAttributes.scalDensity+0.5f);
            text_ChineseName.setLayoutRefreshedListener(null);
            text_InternationalName.setLayoutRefreshedListener(null);
            text_DesignerName.setLayoutRefreshedListener(null);
            text_VersionCode.setLayoutRefreshedListener(null);
            text_ChineseName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_InternationalName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_DesignerName.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_VersionCode.setWidth(ComponentContainer.LayoutConfig.MATCH_CONTENT);
            text_ChineseName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_InternationalName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_DesignerName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
            text_VersionCode.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        }catch (Exception e){}
    }

    private class PacThemeEventHandler extends EventHandler
    {
        private PacThemeEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null)
            {
                return;
            }
            isSuccess = false;
            BigSuccess = false;
            ProcessManager.setThreadPriority(-20);
            String workPath = getCacheDir() + "/VideoUnlockTheme";
            File WorkStorage = new File(workPath);
            if(WorkStorage.exists())FileManager.deleteDirectory(workPath,true,false);
            new File(workPath+"/preview").mkdirs();
            FileManager.copyDir(getFilesDir()+"/ThemesTemplate/unlock_video",workPath+"/unlock");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/preview/preview_icons_0.jpg",workPath+"/preview/preview_icons_0.jpg");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/icons",workPath+"/icons");
            FileManager.copyFile(getFilesDir()+"/ThemesTemplate/description.xml",workPath+"/description.xml");
            File xmlFile = new File(workPath+"/description.xml");
            try
            {
                FileInputStream in = new FileInputStream(xmlFile);
                byte[] b = new byte[(int) xmlFile.length()];
                in.read(b);
                String xmlText = new String(b);
                in.close();
                xmlText = xmlText.replaceAll("汉语名称",textBox_ChineseName.getText());
                xmlText = xmlText.replaceAll("国际名称",textBox_InternationalName.getText());
                xmlText = xmlText.replaceAll("设计师名",textBox_DesignerName.getText());
                xmlText = xmlText.replaceAll("版本号码",textBox_VersionCode.getText());
                xmlText = xmlText.replaceAll("简介信息",textBox_BriefInfo.getText());
                FileOutputStream out = null;
                try
                {
                    out = new FileOutputStream(xmlFile);
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
                    writer.write(xmlText);
                    writer.close();
                    out.flush();
                    out.close();
                }catch(IOException ex){ex.printStackTrace();}
                finally
                {
                    try
                    {
                        if (out != null)
                        {
                            out.close();
                        }
                    } catch(IOException e){}
                }
            }catch(IOException ex) {}
            if((new File(getCacheDir()+"/dawnlighti_unlock_video.mp4")).exists())
            {
                FileManager.copyFile(getCacheDir()+"/dawnlighti_unlock_video.mp4",workPath+"/unlock/ucdscreenlock/unlock.mp4");
            }else
            {
                String UriString = DatabaseManager.getString("UnlockPlusAbility_VideoUri","None");
                if(!UriString.equals("None"))
                {
                    Uri uri_rec =Uri.parse(UriString);
                    DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(getContext());
                    try
                    {
                        InputStream inputStream = null;
                        OutputStream outputStream = null;
                        try
                        {
                            inputStream = new FileInputStream(dataAbilityHelper.openFile(uri_rec, "r"));
                            outputStream = new FileOutputStream(workPath+"/unlock/ucdscreenlock/unlock.mp4");
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length=inputStream.read(buffer))>0)
                            {
                                outputStream.write(buffer,0,length);
                            }
                        }finally
                        {
                            inputStream.close();
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (Exception e) {}
                }
            }
            try
            {
                ImageIntelligent.saveImage(workPath+"/preview/cover.jpg",ImageIntelligent.ResizeImage(showImageArea.getPixelMap(),1080,2160));
                FileManager.copyFile(workPath+"/preview/cover.jpg",workPath+"/preview/preview_unlock_0.jpg");
            }catch (Exception ex){}
            try
            {
                if(!new File(getCacheDir()+"/Project_Themes").exists()) new File(getCacheDir()+"/Project_Themes").mkdirs();
                ZipFileManager.zip(workPath,getCacheDir()+"/Project_Themes/"+textBox_InternationalName.getText()+".hwt");
                InputStream input = null;
                try
                {
                    input = new FileInputStream(getCacheDir()+"/Project_Themes/"+textBox_InternationalName.getText()+".hwt");
                    ValuesBucket valuesBucket = new ValuesBucket();
                    valuesBucket.putString(AVStorage.Downloads.DISPLAY_NAME, textBox_InternationalName.getText()+".hwt");
                    valuesBucket.putString("relative_path", "Download/ThemesEditor/");
                    valuesBucket.putInteger("is_pending", 1);
                    DataAbilityHelper helper = GeneralUtil.createDataAbilityHelper(getContext());
                    int id = helper.insert(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
                    Uri uri = Uri.appendEncodedPathToUri(AVStorage.Downloads.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
                    FileDescriptor fd = helper.openFile(uri, "w");
                    OutputStream output= new FileOutputStream(fd);
                    byte[] buf = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = input.read(buf)) > 0)
                    {
                        output.write(buf, 0, bytesRead);
                    }
                    output.flush();
                    output.close();
                    valuesBucket.clear();
                    valuesBucket.putInteger("is_pending", 0);
                    helper.update(uri, valuesBucket, null);
                    ThemesDate = GeneralUtil.getTimeStr();
                    isSuccess = true;
                    //部分机型未限制存储分区，可直接将主题包复制到/Huawei/Themes目录
                    Files.copy(new File(getCacheDir()+"/Project_Themes/"+textBox_InternationalName.getText()+".hwt").toPath(),new File("/storage/emulated/0/Huawei/Themes/"+ThemesDate+".hwt").toPath(), StandardCopyOption.REPLACE_EXISTING);
                    BigSuccess = true;
                }catch (Exception ex) {ex.printStackTrace();}
                finally {input.close();}
            }catch (Exception e){e.printStackTrace();}
            mainThreadEventHandler.sendEvent(0,0,EventHandler.Priority.IMMEDIATE);
        }
    }

    private class MainThreadEventHandler extends EventHandler
    {
        private MainThreadEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null)
            {
                return;
            }
            String FilePath = "";
            if(BigSuccess)
            {
                FilePath = "Huawei/Themes/"+ThemesDate+".hwt";
                new GeneralToast(getContext())
                        .setText(Toast_Theme_SaveFinish+FilePath)
                        .show();
            }else
            {
                FilePath = "Download/ThemesEditor/"+textBox_InternationalName.getText()+".hwt";
                new GeneralToast(getContext())
                        .setText(isSuccess?(Toast_Theme_SaveFinish+FilePath):Toast_Theme_SaveFailed)
                        .show();
            }
            isProcessing = false;
            textBox_ChineseName.setEnabled(true);
            textBox_InternationalName.setEnabled(true);
            textBox_DesignerName.setEnabled(true);
            textBox_VersionCode.setEnabled(true);
            textBox_BriefInfo.setEnabled(true);
            textBox_ChineseName.setClickedListener(null);
            textBox_InternationalName.setClickedListener(null);
            textBox_DesignerName.setClickedListener(null);
            textBox_VersionCode.setClickedListener(null);
            textBox_BriefInfo.setClickedListener(null);
            screenEventHandler.sendSyncEvent(0,EventHandler.Priority.IMMEDIATE);
        }
    }

    private class ScreenEventHandler extends EventHandler
    {
        private ScreenEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if(event == null) return;
            if(event.eventId == 0) {try{getWindow().clearFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);}catch (Exception e){}}
            else {try{getWindow().addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS);}catch (Exception e){}}
        }
    }

    @Override
    public void onStart(Intent intent)
    {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_unlock_plus);
        this.getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xF7EDD8));
        this.getWindow().setNavigationBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_navigationbar_normal,0xF7EDD8));
        int CurrentColorMode = getColorMode();
        if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
        else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
        this.getWindow().setBackgroundColor(RgbColor.fromArgbInt(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xFEEFF4)));
        ThemesEditorAbility.Instance.eventRunner = EventRunner.current();
        mainThreadEventHandler = new MainThreadEventHandler(EventRunner.current());
        screenEventHandler = new ScreenEventHandler(EventRunner.current());
        GeneralUtil.setWindowToMaxRefreshRate(getWindow());
        GeneralUtil.setWindowSoftInputMode(getWindow(),GeneralUtil.SOFT_INPUT_ADJUST_PAN);
        try
        {
            if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
            {
                if (canRequestPermission("ohos.permission.READ_USER_STORAGE")&&canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
                    requestPermissionsFromUser(new String[] { "ohos.permission.READ_USER_STORAGE","ohos.permission.WRITE_USER_STORAGE"} ,2);
            }
        }catch(Exception ex){}
        ResourceManager resManager = getResourceManager();
        try
        {
            Dialog_Title = resManager.getElement(ResourceTable.String_Dialog_Title).getString();
            Dialog_Content_StoragePermissionFailed = resManager.getElement(ResourceTable.String_Dialog_Content_StoragePermissionFailed).getString();
            Dialog_Button_Cancel = resManager.getElement(ResourceTable.String_Dialog_Button_Cancel).getString();
            Dialog_Button_Confirm = resManager.getElement(ResourceTable.String_Dialog_Button_Confirm).getString();
            Toast_NoneName = resManager.getElement(ResourceTable.String_ThemeToast_NoneName).getString();
            Toast_NoneDesigner = resManager.getElement(ResourceTable.String_ThemeToast_NoneDesigner).getString();
            Toast_NoneVersion = resManager.getElement(ResourceTable.String_ThemeToast_NoneVersion).getString();
            Toast_NoneBriefInfo = resManager.getElement(ResourceTable.String_ThemeToast_NoneBriefInfo).getString();
            Toast_NoneVideo = resManager.getElement(ResourceTable.String_ThemeToast_NoneVideo).getString();
            Toast_IsProcessing = resManager.getElement(ResourceTable.String_ThemeToast_IsProcessing).getString();
            Toast_Theme_SaveFinish = resManager.getElement(ResourceTable.String_ThemeToast_SaveFinish).getString();
            Toast_Theme_SaveFailed = resManager.getElement(ResourceTable.String_ThemeToast_SaveFailed).getString();
        }catch (Exception e){}
        isProcessing = false;
        VideoCached = false;
        textBox_ChineseName = (TextField) findComponentById(ResourceTable.Id_textBox_chineseName);
        textBox_InternationalName = (TextField) findComponentById(ResourceTable.Id_textBox_internationalName);
        textBox_DesignerName = (TextField) findComponentById(ResourceTable.Id_textBox_designerName);
        textBox_VersionCode = (TextField) findComponentById(ResourceTable.Id_textBox_versionCode);
        textBox_BriefInfo = (TextField) findComponentById(ResourceTable.Id_textBox_briefInfo);
        TextBoxManager.TextBoxForStyle(this,textBox_ChineseName);
        TextBoxManager.TextBoxForStyle(this,textBox_InternationalName);
        TextBoxManager.TextBoxForStyle(this,textBox_DesignerName);
        TextBoxManager.TextBoxForStyle(this,textBox_VersionCode);
        TextBoxManager.TextBoxForStyle(this,textBox_BriefInfo);
        DatabaseManager.Init(this);
        textBox_ChineseName.setText(DatabaseManager.getString("UnlockPlus_ChineseName"));
        textBox_InternationalName.setText(DatabaseManager.getString("UnlockPlus_InternationalName"));
        textBox_DesignerName.setText(DatabaseManager.getString("UnlockPlus_DesignerName"));
        textBox_VersionCode.setText(DatabaseManager.getString("UnlockPlus_VersionCode"));
        textBox_BriefInfo.setText(DatabaseManager.getString("UnlockPlus_BriefInfo"));
        textBox_ChineseName.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_ChineseName.setText(TextManager.removeSpecificCharArray(textBox_ChineseName.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("UnlockPlus_ChineseName",textBox_ChineseName.getText());
            }
            catch (Exception e){}
        });
        textBox_InternationalName.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_InternationalName.setText(TextManager.removeSpecificCharArray(textBox_InternationalName.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("UnlockPlus_InternationalName",textBox_InternationalName.getText());
            }
            catch (Exception e){}
        });
        textBox_DesignerName.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_DesignerName.setText(TextManager.removeSpecificCharArray(textBox_DesignerName.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("UnlockPlus_DesignerName",textBox_DesignerName.getText());
            }
            catch (Exception e){}
        });
        textBox_VersionCode.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                String VersionCodeText = "";
                char[] texts = textBox_VersionCode.getText().toCharArray();
                char last = '?';
                for(int o=0;o<texts.length;o++)
                {
                    if(TextManager.isNumChar(texts[o]))
                    {
                        if(texts[o]!=last||texts[o]!='.')
                        {
                            VersionCodeText += texts[o];
                            last = texts[o];
                        }
                    }
                }
                if(VersionCodeText.startsWith("."))
                {
                    VersionCodeText = "12"+VersionCodeText;
                }else if(VersionCodeText.startsWith("0"))
                {
                    VersionCodeText = "12";
                }else if(VersionCodeText.startsWith("0.")||VersionCodeText.startsWith("1.")||VersionCodeText.startsWith("2.")||VersionCodeText.startsWith("3.")||VersionCodeText.startsWith("4.")||VersionCodeText.startsWith("5.")||VersionCodeText.startsWith("6.")||VersionCodeText.startsWith("7.")||VersionCodeText.startsWith("8.")||VersionCodeText.startsWith("9.")||VersionCodeText.startsWith("10.")||VersionCodeText.startsWith("11."))
                {
                    VersionCodeText = "12"+VersionCodeText.substring(VersionCodeText.indexOf('.'));
                }
                textBox_VersionCode.setText(VersionCodeText);
                DatabaseManager.Init(this);
                DatabaseManager.setString("UnlockPlus_VersionCode",VersionCodeText);
            }
            catch (Exception e){}
        });
        textBox_BriefInfo.addTextObserver((s, i, i1, i2) ->
        {
            try
            {
                textBox_BriefInfo.setText(TextManager.removeSpecificCharArray(textBox_BriefInfo.getText()));
                DatabaseManager.Init(this);
                DatabaseManager.setString("UnlockPlus_BriefInfo",textBox_BriefInfo.getText());
            }
            catch (Exception e){}
        });
        text_ChineseName = findComponentById(ResourceTable.Id_text_chineseName);
        text_InternationalName = findComponentById(ResourceTable.Id_text_internationalName);
        text_DesignerName = findComponentById(ResourceTable.Id_text_designerName);
        text_VersionCode = findComponentById(ResourceTable.Id_text_versionCode);
        DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
        int maxTextWidth = displayAttributes.width-(int)(216f*displayAttributes.scalDensity+0.5f);
        text_ChineseName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        text_InternationalName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        text_DesignerName.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        text_VersionCode.setLayoutRefreshedListener(c->{if(c.getWidth()>maxTextWidth)c.setWidth(maxTextWidth);});
        showImageArea = (Image) findComponentById(ResourceTable.Id_showImageArea);
        showImageArea.setPixelMap(GeneralUtil.getPixelMapFromResource(this,ResourceTable.Media_AddPicturesArea));
        showImageArea.setCornerRadius(12f*displayAttributes.scalDensity);
        showImageArea.setClickedListener(c ->
        {
            if(!isProcessing)
            {
                try
                {
                    if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                        showPermissionRequest();
                    else{selectVideo();}
                }catch(Exception ex){}
            }else
            {
                new GeneralToast(this).setText(Toast_IsProcessing).show();
            }
        });
        Button Button_StartProcess= (Button) findComponentById(ResourceTable.Id_Button_StartProcess);
        int spacingHorizontal = (int) ResourceTool.getFloat(this, ResourceTable.Float_spacing_ui_button, 0);
        Button_StartProcess.setBackground(new GeneralButtonElement(this, GeneralButtonElement.TYPE_UI_Button));
        Button_StartProcess.setTextColor(new Color(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_button_text_accent, 0xFFFFFF)));
        Button_StartProcess.setMultipleLine(false);
        Button_StartProcess.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
        Button_StartProcess.setPaddingLeft(spacingHorizontal);
        Button_StartProcess.setPaddingRight(spacingHorizontal);
        Button_StartProcess.setClickedListener(c->
        {
            if(VideoCached)
            {
                if(!isProcessing)
                {
                    if(verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                        showPermissionRequest();
                    else if(textBox_ChineseName.getText().equals("")&&textBox_InternationalName.getText().equals(""))
                        new GeneralToast(this).setText(Toast_NoneName).show();
                    else if(textBox_DesignerName.getText().equals(""))
                        new GeneralToast(this).setText(Toast_NoneDesigner).show();
                    else if(textBox_VersionCode.getText().equals(""))
                        new GeneralToast(this).setText(Toast_NoneVersion).show();
                    else if(textBox_BriefInfo.getText().equals(""))
                        new GeneralToast(this).setText(Toast_NoneBriefInfo).show();
                    else if(!PreloadServiceAbility.isSuccess)
                        new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_ThemeToast_EnvironmentNotReady,"智慧意识未就绪，请确保必要支持库已成功部署！")).show();
                    else
                    {
                        isProcessing = true;
                        textBox_ChineseName.setEnabled(false);
                        textBox_InternationalName.setEnabled(false);
                        textBox_DesignerName.setEnabled(false);
                        textBox_VersionCode.setEnabled(false);
                        textBox_BriefInfo.setEnabled(false);
                        textBox_ChineseName.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                        textBox_InternationalName.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                        textBox_DesignerName.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                        textBox_VersionCode.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                        textBox_BriefInfo.setClickedListener(i->new GeneralToast(this).setText(Toast_IsProcessing).show());
                        if(textBox_ChineseName.getText().equals("")) textBox_ChineseName.setText(textBox_InternationalName.getText());
                        else if(textBox_InternationalName.getText().equals("")) textBox_InternationalName.setText(textBox_ChineseName.getText());
                        String ThemeVersion = textBox_VersionCode.getText();
                        if(!ThemeVersion.contains("."))
                        {
                            ThemeVersion += ".0";
                        }else if(ThemeVersion.endsWith("."))
                        {
                            ThemeVersion += "0";
                        }
                        if(ThemeVersion.startsWith("0.")||ThemeVersion.startsWith("1.")||ThemeVersion.startsWith("2.")||ThemeVersion.startsWith("3.")||ThemeVersion.startsWith("4.")||ThemeVersion.startsWith("5.")||ThemeVersion.startsWith("6.")||ThemeVersion.startsWith("7.")||ThemeVersion.startsWith("8.")||ThemeVersion.startsWith("9.")||ThemeVersion.startsWith("10.")||ThemeVersion.startsWith("11."))
                        {
                            ThemeVersion = "12"+ThemeVersion.substring(ThemeVersion.indexOf('.'));
                        }
                        textBox_VersionCode.setText(ThemeVersion);
                        screenEventHandler.sendSyncEvent(1,EventHandler.Priority.IMMEDIATE);
                        PacThemeEventHandler.sendEvent(0, 0, EventHandler.Priority.IMMEDIATE);
                    }
                }else
                {
                    new GeneralToast(this).setText(Toast_IsProcessing).show();
                }
            }else
            {
                new GeneralToast(this).setText(Toast_NoneVideo).show();
            }
        });
        Component Actionbar_Back_Item_Pressed = findComponentById(ResourceTable.Id_actionBar_Back_Pressed_Item);
        Component Actionbar_Back_Button = findComponentById(ResourceTable.Id_actionBar_Back);
        Actionbar_Back_Button.setClickedListener(c->onBackPressed());
        Actionbar_Back_Button.setComponentStateChangedListener((c,i) ->
        {
            if(i == 18432)
                Actionbar_Back_Item_Pressed.setVisibility(Component.VISIBLE);
            else
                Actionbar_Back_Item_Pressed.setVisibility(Component.INVISIBLE);
        });
        DatabaseManager.Init(this);
        String Ability_QuitBySelf = DatabaseManager.getString("UnlockPlusAbility_QuitBySelf","No");
        if(!Ability_QuitBySelf.equals("Yes"))
        {
            String UriString = DatabaseManager.getString("UnlockPlusAbility_VideoUri","None");
            if(!UriString.equals("None"))
            {
                Uri uri_rec =Uri.parse(UriString);
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                FileDescriptor fd = null;
                try
                {
                    fd = dataAbilityHelper.openFile(uri_rec, "r");
                    AVMetadataHelper avMetadataHelper = new AVMetadataHelper ();
                    avMetadataHelper.setSource(fd);
                    Player player = new Player(this);
                    player.setSource(new Source(fd));
                    player.prepare();
                    int totalTime = player.getDuration();
                    PixelMap pixelMap_rec = avMetadataHelper.fetchVideoPixelMapByTime((long)(totalTime*0.3f), 0x00);
                    if(pixelMap_rec != null)
                    {
                        showImageArea.setPixelMap(pixelMap_rec);
                        VideoCached = true;
                    }
                } catch (Exception e) {}
            }
        }
        DatabaseManager.setString("UnlockPlusAbility_QuitBySelf","No");
        PacThemeEventHandler = new PacThemeEventHandler(EventRunner.create(true));
    }

    @Override
    public void onBackPressed()
    {
        if(!isProcessing)
        {
            DatabaseManager.Init(this);
            DatabaseManager.setString("LastAbilityName","None");
            DatabaseManager.setString("UnlockPlusAbility_QuitBySelf","Yes");
            DatabaseManager.setString("UnlockPlusAbility_VideoUri", "None");
            try{getWindow().setNavigationBarColor(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_navigationbar_bottom, 0xF5F1E6));}catch (Exception ex){}
            ThemesEditorAbility.isMainSceneSlice = true;
            try{showImageArea.release();}catch(Exception e){}
            try{textBox_ChineseName.release();}catch(Exception e){}
            try{textBox_InternationalName.release();}catch(Exception e){}
            try{textBox_DesignerName.release();}catch(Exception e){}
            try{textBox_VersionCode.release();}catch(Exception e){}
            try{textBox_BriefInfo.release();}catch(Exception e){}
            try{text_ChineseName.release();}catch(Exception e){}
            try{text_InternationalName.release();}catch(Exception e){}
            try{text_DesignerName.release();}catch(Exception e){}
            try{text_VersionCode.release();}catch(Exception e){}
            showImageArea=null;
            textBox_ChineseName = null;
            textBox_InternationalName = null;
            textBox_DesignerName = null;
            textBox_VersionCode = null;
            textBox_BriefInfo = null;
            text_ChineseName = null;
            text_InternationalName = null;
            text_DesignerName = null;
            text_VersionCode = null;
            Dialog_Title = null;
            Dialog_Content_StoragePermissionFailed = null;
            Dialog_Button_Cancel = null;
            Dialog_Button_Confirm = null;
            Toast_NoneName = null;
            Toast_NoneDesigner = null;
            Toast_NoneVersion = null;
            Toast_NoneBriefInfo = null;
            Toast_NoneVideo = null;
            Toast_IsProcessing = null;
            Toast_Theme_SaveFinish = null;
            Toast_Theme_SaveFailed = null;
            mainThreadEventHandler = null;
            PacThemeEventHandler = null;
            screenEventHandler = null;
            System.gc();
            if(ThemesEditorAbility.LayoutChanged)
            {
                ThemesEditorAbility.LayoutChanged = false;
                try{MainSceneSlice.Instance.restart();}catch (Exception ex){}
            }
            else
            {
                try{MainSceneSlice.Instance.pageSwiper.ReturnImageSwiper_Industry(true);}catch (Exception ex){}
            }
            super.onBackPressed();
        }else
        {
            new GeneralToast(this).setText(Toast_IsProcessing).show();
        }
    }

    public void PermissionRouter(GeneralDialog dialog)
    {
        Intent e = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS)
                .withUri(Uri.getUriFromParts("package",getBundleName(),null))
                .build();
        e.setOperation(operation);
        startAbility(e);
        dialog.remove();
    }

    private void showPermissionRequest()
    {
        if (canRequestPermission("ohos.permission.READ_USER_STORAGE") && canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
            requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_USER_STORAGE"}, 2);
        else
        {
            GeneralDialog.Builder builder = new GeneralDialog.Builder(getContext());
            builder.setTitle(Dialog_Title)
                    .setContent(Dialog_Content_StoragePermissionFailed)
                    .addButton(Dialog_Button_Cancel, GeneralButtonElement.TYPE_NORMAL, GeneralDialog::remove)
                    .addButton(Dialog_Button_Confirm, GeneralButtonElement.TYPE_ACCENT, this::PermissionRouter)
                    .setOutsideTouchClosable(false)
                    .setMovable(false)
                    .create()
                    .show();
        }
    }

    private void selectVideo()
    {
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder()
                .withAction("android.intent.action.OPEN_DOCUMENT")
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .build();
        intent.setOperation(opt);
        intent.setType("video/mp4");
        startAbilityForResult(intent,ChooseVideo);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData)
    {
        if(requestCode==ChooseVideo)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String VideoUri=resultData.getUriString();
                Uri targetUri;
                if(VideoUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                }else
                {
                    String VideoId;
                    if(VideoUri.lastIndexOf("%3A")!=-1)VideoId = VideoUri.substring(VideoUri.lastIndexOf("%3A")+3);
                    else VideoId = VideoUri.substring(VideoUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI,VideoId);
                }
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                try
                {
                    FileDescriptor fd = dataAbilityHelper.openFile(targetUri, "r");
                    if(FileManager.getFileSize(fd)>80*1048576)
                    {
                        new GeneralToast(this).setText(ResourceTool.getString(this,ResourceTable.String_ThemeToast_VideoTooLarge,"文件过大，请选择80MB以内的视频！")).show();
                    }else
                    {
                        DatabaseManager.Init(this);
                        DatabaseManager.setString("UnlockPlusAbility_VideoUri",targetUri.toString());
                        AVMetadataHelper avMetadataHelper = new AVMetadataHelper ();
                        avMetadataHelper.setSource(fd);
                        Player player = new Player(this);
                        Source source = new Source(fd);
                        player.setSource(source);
                        player.prepare();
                        int totalTime = player.getDuration();
                        PixelMap pixelMap =  avMetadataHelper.fetchVideoPixelMapByTime((long)(totalTime*0.3f), 0x00);
                        showImageArea.setPixelMap(pixelMap);
                        InputStream inputStream = null;
                        OutputStream outputStream = null;
                        try
                        {
                            //必须重新获取FileDescriptor，否则文件会因为前置操作而残缺不可用
                            inputStream = new FileInputStream(dataAbilityHelper.openFile(targetUri, "r"));
                            outputStream = new FileOutputStream(getCacheDir()+"/dawnlighti_unlock_video.mp4");
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length=inputStream.read(buffer))>0)
                            {
                                outputStream.write(buffer,0,length);
                            }
                            outputStream.flush();
                            outputStream.close();
                            VideoCached = true;
                        }finally
                        {
                            try
                            {
                                if (outputStream != null)
                                    outputStream.close();
                                if(inputStream != null)
                                    inputStream.close();
                            } catch(IOException e){}
                        }
                    }
                } catch (Exception e) {new GeneralToast(this).setText(e.getMessage()).show();} finally {}
            }catch (Exception e){}
        }
    }

    @Override
    public void onActive() {super.onActive();}

    @Override
    public void onForeground(Intent intent) {super.onForeground(intent);}
}